const {ccclass, property} = cc._decorator;

@ccclass
export default class Buttle extends cc.Component {
    target:cc.Node = null;
    dir:cc.Vec2 = cc.Vec2.ZERO
    speed:number = 600

    onLoad(){
        // this.target = this.node.parent.getComponent(Tower).target
    }
    update(dt){
        this.lookAtTarget()
        this.moveToTarget(dt)
    }

    lookAtTarget(){
        if(this.target != null){
            //计算向量值
            const offset = this.target.getPosition().sub(this.node.getPosition())
            //向量差的单位向量
            this.dir = offset.normalize()
            //求与垂直方向的夹角
            const radian = offset.angle(cc.Vec2.UP)
            //弧度转角度
            let angle = (radian * 180) / Math.PI 
            //设置旋转角度
            this.node.angle = offset.x < 0 ? angle : -angle
        }
    }

    moveToTarget(dt){
        const tranlation = this.dir.mul(dt * this.speed)
        let pos = this.node.getPosition()
        pos = pos.add(tranlation)
        this.node.setPosition(pos)
    }
}
